package com.eportal.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

/**
 * Created by smzhang on 2015/12/17.
 */
public class UploadUtil {
	private static Map<String, Object> result = new HashMap<String, Object>();
	private static Logger log = Logger.getLogger(UploadUtil.class);

    /**
     * 通过文件名获取文件后缀
     *
     * @param fileName
     * @return
     */
    public static String getExt(String fileName) {
        int position = fileName.lastIndexOf(".");
        return fileName.substring(position);
    }


    /**
     * 文件复制
     *
     * @param sourceFile 源文件
     * @param destFile   目标文件
     * @throws IOException
     */
    public static void store(File sourceFile, File destFile) throws IOException {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(sourceFile);
            outputStream = new FileOutputStream(destFile);
            byte[] bytes = new byte[512];
            while (inputStream.read(bytes) != -1) {
                outputStream.write(bytes);
            }
        } finally {
            inputStream.close();
            outputStream.close();
        }
    }
    
    /**
	 * @Description: 文件上传
	 * @param file
	 * @param fileName
     * @param path 
	 * @return
	 */
	 public static Map<String, Object> uplodeFile(File file, String fileName, String path) {
		 try {
			 String destFileName = null;
              if (file.length() > 5 * 1024000) {
            	 result.put("code", 0);
            	 result.put("msg", "文件大小不能大于5M");
                 return result;
             } else {
                 // 保存上传文件
                 String ext = UploadUtil.getExt(fileName);
                 String destDir = ServletActionContext.getRequest().getServletContext().getRealPath(path);
                 if (!new File(destDir).exists()) {
						new File(destDir).mkdirs();
					}
                 destFileName = System.currentTimeMillis() + ext;
				 store(file, new File(destDir, destFileName));
             }
	    	result.put("agtAttr", path + destFileName);
	    	result.put("code", 1);
	    	result.put("msg", "上传成功");
		 } catch (IOException e) {
			 log.error("error",e);
			 result.put("code", 0);
        	 result.put("msg", "文件上传失败");
			}
    	return result;
	}
	 
	 public static HttpServletResponse download(String path, String fileName, HttpServletResponse response) {
	        try {
	            // path是指欲下载的文件的路径。
	            File file = new File(path,fileName);
	            // 取得文件的后缀名。
	            String ext = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();
	            // 以流的形式下载文件。
	            InputStream fis = new BufferedInputStream(new FileInputStream(path+File.separator+fileName));
	            byte[] buffer = new byte[fis.available()];
	            fis.read(buffer);
	            fis.close();
	            // 清空response
	            response.reset();
	            // 设置response的Header
//	            response.setContentType("application/vnd.ms-excel");  
	            response.setContentType("application/octet-stream");
	            response.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
	            response.addHeader("Content-Length", "" + file.length());
	            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
	            toClient.write(buffer);
	            toClient.flush();
	            toClient.close();
	        } catch (IOException ex) {
	        	log.error("error",ex);
	        }
	        return response;
	    }

	    public void downloadLocal(HttpServletResponse response) throws FileNotFoundException {
	        // 下载本地文件
	        String fileName = "Operator.doc".toString(); // 文件的默认保存名
	        // 读到流中
	        InputStream inStream = new FileInputStream("c:/Operator.doc");// 文件的存放路径
	        // 设置输出的格式
	        response.reset();
	        response.setContentType("bin");
	        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
	        // 循环取出流中的数据
	        byte[] b = new byte[100];
	        int len;
	        try {
	            while ((len = inStream.read(b)) > 0)
	                response.getOutputStream().write(b, 0, len);
	            inStream.close();
	        } catch (IOException e) {
	        	log.error("error",e);
	        }
	    }

	    public void downloadNet(HttpServletResponse response) throws MalformedURLException {
	        // 下载网络文件
	        int bytesum = 0;
	        int byteread = 0;

	        URL url = new URL("windine.blogdriver.com/logo.gif");

	        try {
	            URLConnection conn = url.openConnection();
	            InputStream inStream = conn.getInputStream();
	            FileOutputStream fs = new FileOutputStream("c:/abc.gif");

	            byte[] buffer = new byte[1204];
	            int length;
	            while ((byteread = inStream.read(buffer)) != -1) {
	                bytesum += byteread;
	                System.out.println(bytesum);
	                fs.write(buffer, 0, byteread);
	            }
	        } catch (FileNotFoundException e) {
	        	log.error("error",e);
	        } catch (IOException e) {
	        	log.error("error",e);
	        }
	    }
}
